/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2022-01-09 15:53:04
 * 天凉好个秋
 */
import { defineStore } from 'pinia'
import{ IPlayStore, playMode, songTime } from '@/types/store/playStoreType'
import { IAllObject } from '@/types/base'
import { useSong } from '@/hooks/song/useSong'
import { useLocalStorage } from '@/hooks/localStorage/useLocalStorage'
import { notEmptyObj } from '@/utils/util'
const { getSongName, getSingers, getSongTime } = useSong()
const { getStorageItem, setStorageItem } = useLocalStorage()

export const usePlayStore = defineStore({
  id: 'play',
  state: (): IPlayStore =>({
    songId: getStorageItem('songId'),
    url: undefined,
    volume: getStorageItem('volume') || 1,
    detail: getStorageItem('songDetail') || {},
    lyric: getStorageItem('lyric') || "暂无歌词",
    isPlaying: false,
    inPlayPage: false,
    playList: getStorageItem('playList') || [],
    playHistory: getStorageItem('playHistory') || [],
    currentPlayTime: 0,
    playMode: getStorageItem('playMode') || playMode.顺序播放
  }),
  getters: {
    // 获取歌曲名称
    name(): string {
      if(notEmptyObj(this.detail)) return getSongName(this.detail.name, this.detail.alia)
      return '未知作品'
    },
    // 获取封面
    cover(): string | undefined {      
      if(notEmptyObj(this.detail)) return this.detail.al.picUrl
      return undefined
    },
    // 获取歌手
    singer(): string {
      if(notEmptyObj(this.detail)) return getSingers(this.detail.ar)
      return '未知艺术家'
    },
    // 获取歌曲时间
    songTime(): songTime {
      if(notEmptyObj(this.detail)) return {
        time: Number((this.detail.dt / 1000).toFixed(2)),
        timeStr: getSongTime(this.detail.dt)
      }
      return {
        time: 0,
        timeStr: '00:00'
      }
    }
  },
  actions: {
    // 设置是否处于歌曲详情页面，不传状态则取反
    toggleInPlayPage(flag?: boolean) {
      if(flag === undefined) return this.inPlayPage = !this.inPlayPage
      this.inPlayPage = flag
    },
    // 设置是否正在播放中，不传状态则取反
    toggleIsPlaying(flag?: boolean) {
      if(flag === undefined) return this.isPlaying = !this.isPlaying;
      this.isPlaying = flag
    },
    // 设置id
    setId(id: number) {
      this.songId = id
      setStorageItem('songId', id)
    },
    // 设置音量
    setVolume(volume: number) {
      this.volume = volume
      setStorageItem('volume', volume)
    },
    // 设置播放地址
    setUrl(url?: string) {
      this.url = url
    },
    // 设置详情
    setDetail(detail: IAllObject) {
      this.detail = detail
      setStorageItem('songDetail', detail)
    },
    // 设置歌词
    setLyric(lyric: string) {
      this.lyric = lyric
      setStorageItem('lyric', lyric)
    },
    // 设置播放模式
    setPlayMode(mode: playMode) {
      this.playMode = mode
      setStorageItem('playMode', mode)
    },
    // 设置播放列表
    setPlayList(list: any[]) {
      this.playList = list
      setStorageItem('playList', list)
    },
    // 设置播放记录列表
    setPlayHistory(list: number[]) {
      this.playHistory = list
      setStorageItem('playHistory', list)
    }
  }
})